//
//  ViewController.m
//  BeautifulWardrobe
//
//  Created by mac on 16/7/28.
//  Copyright © 2016年 rongshao. All rights reserved.
//

#import "ViewController.h"
#import "CsutomView.h"
#import "slidingViewCell.h"
#import "FineViewCell.h"
#import "RecommendedViewCell.h"
#import <UIImageView+WebCache.h>
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>
{
    NSArray *_allArray;
    
    NSMutableArray *_productsArray;
    BOOL flag;
    UIView *_zhangKaiView;
    UIScrollView *_scrollView;
    UIButton *zhangshibtn;
    UIView *_lineView;
    UIButton *_btn;
    NSMutableArray *scrollViewArrat;
    NSMutableArray *zhangKaiArrat;
    UIButton *viewBtn;
    slidingViewCell *cell2;
    NSMutableArray *mArray;
    UIImageView *image1;
    MJRefreshGifHeader *header;
    MJRefreshBackGifFooter *footer;

}
@property (nonatomic, strong)UIScrollView *bigScrollView;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, assign)int pageNum;

@end

@implementation ViewController
//赖加载
- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc] init];
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, _bigScrollView.frame.size.height) collectionViewLayout:fl];
        _collectionView.backgroundColor = [UIColor colorWithWhite:0.931 alpha:1.000];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[slidingViewCell class] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerClass:[FineViewCell class] forCellWithReuseIdentifier:@"cell1"];
        [_collectionView registerClass:[RecommendedViewCell class] forCellWithReuseIdentifier:@"cell2"];
    }
    return _collectionView;
}
//大滑动视图
- (UIScrollView *)bigScrollView
{
    if (!_bigScrollView)
    {
        self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 104, WIDTH, HEIGHT - 104)];
        _bigScrollView.contentSize = CGSizeMake(WIDTH * 20, HEIGHT-104);
        _bigScrollView.backgroundColor = [UIColor colorWithWhite:0.826 alpha:1.000];
        _bigScrollView.directionalLockEnabled = YES;
        _bigScrollView.pagingEnabled = YES;
        _bigScrollView.delegate = self;
    }
    return _bigScrollView;
}


//请求数据
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [netRequestMethod sendRequestMethod:@"GET" withRequestURL:@"http://api.yuike.com/gmall/api/1.0/home/floor_list.php?mid=457465" withHttpBodyDic:nil withRequestBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _allArray = dic[@"data"][@"floor_items"];
        [self SmallScrollView];
        [self zhankaiView];
        [self zhangshibtn];
    }];
     [self footNewData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNum = 0;
    _productsArray = [NSMutableArray array];
    _btn = [[UIButton alloc] init];
    flag = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.730 green:0.000 blue:0.000 alpha:1.000];
    
    CsutomView *view = [[CsutomView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    self.navigationItem.titleView = view;
    //禁止默认偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    //添加大滑动视图
    [self.view addSubview:self.bigScrollView];
    //添加CollView
    [self.bigScrollView addSubview:self.collectionView];
    
    [self header];
   
  
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    if (section == 1)
    {
        return 1;
    }
    return self.pageNum;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = nil;
    if (indexPath.section == 0)
    {
        cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell = cell2;
    }
    if (indexPath.section == 1)
    {
        FineViewCell *cell3 = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell1" forIndexPath:indexPath];
        cell = cell3;
        
    }
    if (indexPath.section == 2)
    {
        RecommendedViewCell *cell4 = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
        cell4.backgroundColor = [UIColor whiteColor];
        NSArray *array = [NSArray arrayWithArray:_productsArray];
        [cell4.Img sd_setImageWithURL:[NSURL URLWithString:array[indexPath.row][@"pic_url"]]];
        
        cell4.introduceLabel.text = array[indexPath.row][@"title"];
        cell4.priceLabel.text = [NSString stringWithFormat:@"%@%@",array[indexPath.row][@"money_symbol"],array[indexPath.row][@"selling_price"]];
        cell4.numberLabel.text = array[indexPath.row][@"sales_volume"];
        cell4.layer.cornerRadius = 6;
        cell4.layer.masksToBounds = YES;
        cell4.layer.borderWidth = 1;
        cell4.layer.borderColor = [[UIColor colorWithWhite:0.866 alpha:1.000]CGColor];
        cell = cell4;
    }
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{

    if (section == 2)
    {
        return UIEdgeInsetsMake(0, 5, 0, 5);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
//通过协议方法设置单元格尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return CGSizeMake(WIDTH, HEIGHT / 5);
    }
    if (indexPath.section == 1)
    {
        return CGSizeMake(WIDTH,HEIGHT/5*3+80+ (((HEIGHT/5)*2)-40));
    }
    return CGSizeMake(WIDTH/2-10, WIDTH/2+55);
}
#pragma mark - 展开按钮
//展开button
- (void)zhankaiView
{
    _zhangKaiView = [[UIView alloc] init];
    _zhangKaiView.clipsToBounds = YES;
    _zhangKaiView.userInteractionEnabled = NO;
    _zhangKaiView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_zhangKaiView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
    label.text = @"选择分类";
    label.textColor = [UIColor grayColor];
    [_zhangKaiView addSubview:label];
    
    UIImageView *Img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 2)];
    Img.image = [UIImage imageNamed:@"line_activity"];
    [_zhangKaiView addSubview:Img];
    
     zhangKaiArrat = [NSMutableArray array];
    for (int i = 0; i < 20; i++)
    {
        UIButton * zhangKaibtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        zhangKaibtn.frame = CGRectMake(10 + (i % 4) * (40 + (WIDTH - 20 - 50 *4)/3), 50 + i / 4 * 30, 80, 20);
        [zhangKaibtn setTitle:_allArray[i][@"title"] forState:(UIControlStateNormal)];
        [zhangKaibtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [zhangKaibtn setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        [zhangKaibtn setBackgroundImage:[UIImage imageNamed:@"home_page_more_button"] forState:(UIControlStateNormal)];
        zhangKaibtn.tag = i;
        [zhangKaibtn addTarget:self action:@selector(fenLeiButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
                [zhangKaiArrat addObject:zhangKaibtn];
        [_zhangKaiView addSubview:zhangKaibtn];
        
        if (i==0) {
            zhangKaibtn.selected=YES;
        }
        
    }
        _zhangKaiView.userInteractionEnabled = YES;
        viewBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        viewBtn.backgroundColor = [UIColor colorWithWhite:0.907 alpha:1.000];
        viewBtn.clipsToBounds = YES;
        viewBtn.alpha = 0.3;
        [viewBtn addTarget:self action:@selector(PinMubuttonAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:viewBtn];
   
}
#pragma mark - 展示按钮
- (void)zhangshibtn
{
    zhangshibtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    
    zhangshibtn.frame = CGRectMake(WIDTH - 30, 77, 15, 15);
    
    [zhangshibtn setImage:[UIImage imageNamed:@"image_more_down"] forState:(UIControlStateNormal)];
    
    [zhangshibtn addTarget:self action:@selector(zhangshibtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:zhangshibtn];

}

#pragma mark - 小滑动视图
- (void)SmallScrollView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, WIDTH - 40, 40)];
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(15 + 30 * 20 + 30 * 20, 0);
     scrollViewArrat = [NSMutableArray array];
    for (int i = 0; i < 20; i++)
    {
        UIButton *scrollViewBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        scrollViewBtn.frame = CGRectMake(15 + i * 60, 10, 35, 20);
        scrollViewBtn.tag = i;
        [scrollViewBtn setTitle:_allArray[i][@"title"] forState:(UIControlStateNormal)];
        [scrollViewBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
         [scrollViewBtn setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        scrollViewBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [scrollViewBtn addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
       
        [scrollViewArrat addObject:scrollViewBtn];
        [_scrollView addSubview:scrollViewBtn];
        if (scrollViewBtn.tag == 0)
        {
            _btn = scrollViewBtn;
            _btn.selected = YES;
            _lineView  = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(scrollViewBtn.frame), 38, 35, 2)];
            _lineView.backgroundColor = [UIColor redColor];
            [_scrollView addSubview:_lineView];
        }

    }
    [self.view addSubview:_scrollView];
}

- (void)buttonAction:(UIButton *)btn
{
    [self ScrollViewbuttonAction:btn];
    [self fenLeiButtonAction:btn];
}

//小滑动视图按钮
- (void)ScrollViewbuttonAction:(UIButton *)btn
{
    for (UIButton *button in zhangKaiArrat)
    {
        button.selected = NO;
        if (button.tag == btn.tag)
        {
            button.selected = YES;
        }
    }

    [UIView animateWithDuration:.5 animations:^
     {
    _lineView.frame = CGRectMake(btn.frame.origin.x, 38, 35, 2);
     }];
  
}
//大滑动视图

//分类Button
- (void)fenLeiButtonAction:(UIButton *)btn
{
    for (UIButton *button in scrollViewArrat)
    {
        button.selected = NO;
        if (button.tag == btn.tag)
        {
            button.selected = YES;
            [UIView animateWithDuration:.5 animations:^
             {
                 _lineView.frame = CGRectMake(button.frame.origin.x, 38, 35, 2);
                 
             }];
     
        }
  
    }
    for (UIButton *imgButton in zhangKaiArrat) {
        imgButton.selected=NO;
        if (btn.tag==imgButton.tag) {
            imgButton.selected=YES;
        }
        
    }

}
//展开按钮
- (void)zhangshibtnAction:(UIButton *)btn
{
    if (flag)
    {
        viewBtn.frame = CGRectMake(0, 192+104, self.view.frame.size.width, HEIGHT - self.view.frame.size.height / 3 - 50);
        [UIView animateWithDuration:0.25 animations:^{
            btn.transform = CGAffineTransformMakeRotation(M_PI);
            _zhangKaiView.frame = CGRectMake(0, 64, self.view.frame.size.width, 192);
            _scrollView.frame = CGRectMake(0, 0, 0, 0);
           
        } completion:^(BOOL finished) {
            flag = NO;
        }];
        
    }else
    {
        viewBtn.frame = CGRectZero;
        [UIView animateWithDuration:0.25 animations:^{
            btn.transform = CGAffineTransformMakeRotation(0);
            
            _zhangKaiView.frame = CGRectMake(0, 0, self.view.frame.size.width, 0);
            _scrollView.frame = CGRectMake(0, 64, WIDTH - 40, 40);
            
            
        } completion:^(BOOL finished) {
            flag = YES;
        }];
    }
}

//屏幕View缩回button
- (void)PinMubuttonAction
{
    viewBtn.frame = CGRectZero;
    [UIView animateWithDuration:0.25 animations:^{
        zhangshibtn.transform = CGAffineTransformMakeRotation(0);

        _zhangKaiView.frame = CGRectMake(0, 0, self.view.frame.size.width, 0);
        _scrollView.frame = CGRectMake(0, 64, WIDTH - 40, 40);
    } completion:^(BOOL finished) {
        flag = YES;
    }];
}

//刷新
- (void)header
{
    //下拉
    header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//    image1 = [[UIImageView alloc] init];
//    image1.image = [UIImage imageNamed:@"image_ego_refresh0"];
//    [self.view addSubview:image1];
//    mArray = [NSMutableArray array];
//    for (int i = 0; i < 6; i ++)
//    {
//         UIImage *img=[UIImage imageNamed:[NSString stringWithFormat:@"image_ego_refresh%d",i]];
//         [mArray addObject:img];
//    }
//   
//    NSArray *jieshou = [NSArray arrayWithObject:mArray];
//    // 设置普通状态的动画图片
//    [header setImages:jieshou forState:MJRefreshStateIdle];
//    
//    //    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
//    [header setImages:jieshou forState:MJRefreshStatePulling];
//    ////    // 设置正在刷新状态的动画图片
//    [header setImages:jieshou forState:MJRefreshStateRefreshing];
//    //    // 设置header
    self.bigScrollView.mj_header = header;
    
    //上拉
    footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footNewData)];
    self.bigScrollView.mj_footer = footer;
    
    
}
//下拉
-(void)footNewData
{
    self.pageNum += 40;
    [self HTTP];
}//上拉
-(void)loadNewData
{
    self.pageNum = 40;
    [_productsArray removeAllObjects];
    [self HTTP];
}
//数据请求
-(void)HTTP
{
    NSString *str = @"4796%2C4797%2C4798%2C4805%2C4838%2C4839%2C4840%2C4841%2C4843%2C4892%2C22150%2C22153%2C22155";;
    [netRequestMethod sendRequestMethod:@"GET" withRequestURL:[NSString stringWithFormat:@"http://api.yuike.com/gmall/api/1.0/allbuy/list.php?category_ids=%@&count=40&cursor=%d&mid=457465&sid=69d3713fd6f91d8aca094b75b7af9780&sort=default&type=dress&yk_appid=1&yk_cbv=2.9.5&yk_pid=1&yk_user_id=5198358",str,self.pageNum] withHttpBodyDic:nil withRequestBlock:^(NSData *data) {
        NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array =dic[@"data"][@"products"];
        for (NSDictionary *dic in array) {
            [_productsArray addObject:dic];
        }
        [_collectionView reloadData];
        [_bigScrollView.mj_footer endRefreshing];
        [_bigScrollView.mj_header endRefreshing];
        
    }];

}
//滑动视图已经开始滑动时执行的方法，在滑动的过程中，会持续执行此方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y == -50)
    {
        NSLog(@"6");
    }
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y>0)
    {
        _scrollView.frame = CGRectZero;
        _bigScrollView.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 104);
    }else {
        _scrollView.frame = CGRectMake(0, 64, WIDTH - 40, 40);
        _bigScrollView.frame = CGRectMake(0, 104, WIDTH, HEIGHT - 104);
    }
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
